<template>
  <view class="add-car-page">
    <view class="add-car-section">
      <image class="add-car-illustration" src="/static/car1.png" mode="widthFix"></image>
      <view class="add-car-form">
        <view class="add-car-row">
          <view class="add-car-label">车辆类型</view>
          <picker 
            :range="carTypes" 
            :value="carTypeIndex" 
            @change="onCarTypeChange" 
            class="add-car-input-picker"
          >
            <view class="add-car-input">{{ carTypes[carTypeIndex] ||'请选择' }}</view>
          </picker>
        </view>
        <view class="add-car-row">
          <view class="add-car-label">车辆型号:</view>
          <picker 
            :range="carModels" 
            :value="carModelIndex" 
            @change="onCarModelChange" 
            class="add-car-input-picker"
          >
            <view class="add-car-input">{{ carModels[carModelIndex] || '请选择' }}</view>
          </picker>
        </view>
        <view class="add-car-row">
          <view class="add-car-label">车牌号码</view>
          <input 
            class="add-car-input" 
            placeholder="请输入您的车牌号" 
            v-model="plate" 
          />
        </view>
        <view class="add-car-row">
          <view class="add-car-label">车主姓名</view>
          <input 
            class="add-car-input" 
            placeholder="请输入您的姓名" 
            v-model="owner" 
          />
        </view>
        <view class="add-car-row">
          <view class="add-car-label">电话号码</view>
          <input 
            class="add-car-input" 
            placeholder="请输入您的手机号" 
            v-model="phone" 
            type="number"
          />
        </view>
        <view class="add-car-row add-car-photo-row">
          <view class="add-car-label">照片</view>
          <view class="add-car-photo-upload" @click="chooseImage">
            <image 
              v-if="!photo" 
              class="add-car-photo-placeholder-img" 
              src="/static/car-placeholder.png" 
              mode="aspectFill"
            ></image>
            <view v-if="!photo" class="add-car-photo-placeholder-content">
              <text class="add-car-photo-plus">＋</text>
              <text class="add-car-photo-tip">上传车辆照片</text>
            </view>
            <image 
              v-else 
              class="add-car-photo-img" 
              :src="photo" 
              mode="aspectFill"
            ></image>
          </view>
        </view>
      </view>
    </view>
    <view class="add-car-btn-bar">
      <button class="add-car-btn" @click="submitAddCar">＋ 添加车辆</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import baseUrl from '@/untils/urlConfig';
import unirequest from '@/untils/unirequest';

// 响应式数据
const carTypes = ref([]);
const carTypeIndex = ref('');
const carModels = ref(['奥迪A6', '奔驰-GR', '宝马X5']);
const carModelIndex = ref('');
const plate = ref('');
const owner = ref('');
const phone = ref('');
const photo = ref('');

// 获取当前登录用户ID（用于关联车辆和用户）
const getCurrentUserId = () => {
  // 暂时返回一个固定的模拟用户ID
  return '1'; 
  // 真实的登录判断逻辑（暂时注释）
  // const userInfo = uni.getStorageSync('userInfo');
  // if (!userInfo || !userInfo.userId) {
  //   uni.showToast({
  //     title: '请先登录',
  //     icon: 'none'
  //   });
    // 跳转到登录页面（如果需要）
    // setTimeout(() => {
    //   uni.navigateTo({
    //     url: '/pages/login/login'
    //   });
    // }, 1500);
  //   return null;
  // }
  // return userInfo.userId;
};

// 选择车辆类型
const onCarTypeChange = (e) => {
  carTypeIndex.value = e.detail.value;
  // 车辆型号可能依赖于车辆类型，如果后端有接口获取型号，需要在这里调用
};

// 选择车辆型号
const onCarModelChange = (e) => {
  carModelIndex.value = e.detail.value;
};

// 选择图片
const chooseImage = () => {
  uni.chooseImage({
    count: 1,
    success: (res) => {
      photo.value = res.tempFilePaths[0];
    }
  });
};

// 获取车辆类型列表
const fetchCarTypes = async () => {
    try {
        const response = await unirequest({
            url: baseUrl + '/chy/car_type/list', // 后端获取车辆类型接口地址
            method: 'GET',
          
        });

        // 检查响应状态码和业务状态码
        if (response.statusCode === 200 && response.data && response.data.code === 200) {
            // 假设后端返回的数据列表在 response.data.rows 中
            // 并且每个车辆类型对象有一个表示名称的字段，例如 'typeName' 或 'name'
            carTypes.value = response.data.rows.map(item => item.typeName || item.name || '未知类型'); // 假设后端返回对象中有typeName或name字段
            console.log('获取车辆类型成功:', carTypes.value);
        } else {
            const errorMessage = response.data && response.data.msg ? response.data.msg : '获取车辆类型失败';
            uni.showToast({
                title: errorMessage,
                icon: 'none'
            });
            console.error('获取车辆类型失败:', response);
        }
    } catch (error) {
        console.error('请求车辆类型失败:', error);
        uni.showToast({
            title: '网络请求失败',
            icon: 'none'
        });
    }
};

// 提交添加车辆信息
const submitAddCar = async () => {
  // 简单的表单验证
  if (carTypeIndex.value === '' || carModelIndex.value === '' || !plate.value || !owner.value || !phone.value) {
    uni.showToast({
      title: '请填写完整的车辆信息',
      icon: 'none'
    });
    return;
  }

  const userId = getCurrentUserId();
  if (!userId) {
      // 如果获取不到用户ID（例如返回null），中断提交
      uni.showToast({
          title: '无法获取用户信息，请重试',
          icon: 'none'
      });
      return;
  }

  // 收集表单数据
  const carData = {
    // 假设后端字段名是 type, carNum 等
    type: carTypes.value[carTypeIndex.value], // 车辆类型
    model: carModels.value[carModelIndex.value], // 车辆型号 （后端可能没有这个字段，请根据实际情况调整）
    carNum: plate.value, // 车牌号码
    owner: owner.value, // 车主姓名 （后端可能没有这个字段）
    phone: phone.value, // 电话号码 （后端可能没有这个字段）
    // photo: photo.value, // 照片路径 （可能需要先上传图片）
    uid: userId // 关联用户ID
  };

  console.log('提交的车辆数据:', carData);

  try {
    // 调用后端添加车辆API
    const response = await unirequest({
      url: baseUrl+'/chy/usercarinfo/', // 假设后端添加车辆接口是 POST /usercarinfo
      method: 'POST',
      data: carData, // 发送车辆数据 
      });
      // 跳转到成功页面或车辆列表页面
      if (response.data?.code === 200) {
      uni.showToast({ title: '添加成功', icon: 'success' });
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/car/add-car-success' // 或者跳转到成功页面 /pages/car/add-car-success
        });
      }, 1500);
    } else {
      // 处理后端返回的错误
      const errorMessage = response.data && response.data.msg ? response.data.msg : '添加车辆失败';
      uni.showToast({
        title: errorMessage,
        icon: 'none'
      });
      console.error('添加车辆失败:', response);
    }

  } catch (error) {
    console.error('请求失败:', error);
    uni.showToast({
      title: '网络请求失败',
      icon: 'none'
    });
  }
};

// 页面加载时获取数据
onMounted(() => {
    fetchCarTypes(); // 在页面加载时获取车辆类型
    // fetchCars(); // 如果需要在这里获取车辆列表，可以在添加成功后刷新
});

// 跳转成功页面 (已弃用，功能合并到 submitAddCar)
// const goSuccess = () => {
//   uni.navigateTo({ url: '/pages/car/add-car-success' });
// };
</script>

<style>
.add-car-page {
  background: #fafafa;
  min-height: 100vh;
  font-family: "PingFang SC", "Microsoft YaHei", Arial, sans-serif;
}
.add-car-section {
  background: #fff;
  border-radius: 32rpx;
  margin: 32rpx 18rpx 0 18rpx;
  padding: 32rpx 0 32rpx 0;
  box-shadow: 0 8rpx 32rpx rgba(35,138,255,0.04);
  display: flex;
  flex-direction: column;
  align-items: center;
}
.add-car-illustration {
  width: 450rpx;
  margin-bottom: 80rpx;
  margin-top: 100rpx;
}
.add-car-form {
  width: 92vw;
  max-width: 650rpx;
  margin: 0 auto;
}
.add-car-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  margin-bottom: 28rpx;
}
.add-car-label {
  background: #4da6ff;
  color: #fff;
  font-size: 28rpx;
  border-radius: 32rpx;
  padding: 0 32rpx;
  height: 56rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 500;
  margin-right: 18rpx;
  min-width: 120rpx;
}
.add-car-input, .add-car-input-picker {
  background: #fafbfc;
  border-radius: 32rpx;
  border: 1rpx solid #e5e5e5;
  font-size: 28rpx;
  color: #bbb;
  height: 56rpx;
  line-height: 56rpx;
  flex: 1;
  padding: 0 24rpx;
  box-sizing: border-box;
}
.add-car-input {
  border: none;
  outline: none;
}
.add-car-photo-row {
  align-items: flex-start;
}
.add-car-photo-upload {
  width: 140rpx;
  height: 140rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 16rpx;
  background: #fafbfc;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-left: 18rpx;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.add-car-photo-placeholder-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  position: absolute;
  left: 0; top: 0;
  z-index: 1;
}
.add-car-photo-placeholder-content {
  position: relative;
  z-index: 2;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.add-car-photo-plus {
  font-size: 48rpx;
  color: #bbb;
  margin-bottom: 8rpx;
}
.add-car-photo-tip {
  font-size: 22rpx;
  color: #bbb;
}
.add-car-photo-img {
  width: 100%;
  height: 100%;
  border-radius: 16rpx;
}
.add-car-btn-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 32rpx;
  display: flex;
  justify-content: center;
  z-index: 10;
}
.add-car-btn {
  background: linear-gradient(90deg, #238aff 0%, #4da6ff 100%);
  color: #fff;
  font-size: 36rpx;
  font-weight: 500;
  border-radius: 80rpx;
  padding: 3rpx 0;
  width: 82vw;
  border: none;
  box-shadow: 0 2rpx 8rpx rgba(35,138,255,0.10);
}
</style> 